<template>
  <div>
    <el-card class="edit-user">
      <div>
        <el-upload
          :headers="{ authorization: token }"
          action=https:\\ihrms.lyc.husf.xyz\upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <el-avatar :size="300" fit="contain" :src="user.header"></el-avatar>
        </el-upload>
      </div>
      <!-- 信息展示 -->
      <div>
        <el-form
          ref="elForm"
          :model="user"
          :rules="rules"
          size="medium"
          label-width="81px"
        >
          <el-form-item label="姓名" prop="user">
            <el-input
              v-model="user.user"
              placeholder="请输入姓名"
              clearable
              :style="{ width: '100%' }"
              :disabled="
                ['管理员', '超级管理员'].indexOf(user.user) == -1 ? false : true
              "
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="user.phone"
              placeholder="请输入手机号"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="user.sex"
              placeholder="请选择性别"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in sexOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期" prop="date">
            <el-date-picker
              v-model="user.date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择出生日期"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="faceDialog">录制人脸</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 人脸对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="40%">
      <div class="videodome">
        <div>
          <video
            id="videoCamera"
            width="250"
            height="250"
            autoplay
            style="border-radius: 180px; box-shadow: darkgrey 0 0 30px 5px"
          ></video>
        </div>
        <canvas
          style="display: none"
          id="canvasCamera"
          width="250"
          height="250"
        ></canvas>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="success" @click="setImage()">拍照</el-button>
        <el-button type="primary" @click="openFullScreen1">上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { edituser } from "@/axios/user";
import { mapMutations, mapState } from "vuex";
export default {
  data() {
    // 判断修改的名字
    var validateuser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入姓名"));
      } else if (["超级管理员", "管理员"].indexOf(value) != -1) {
        this.user.user = "";
        this.$message.info("请换一个姓名");
        callback(new Error("请换一个姓名"));
      } else {
        callback();
      }
    };
    return {
      videoWidth: 250,
      videoHeight: 250,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      dialogVisible: false,
      rules: {
        user: [{ validator: validateuser, trigger: "blur" }],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
            trigger: "change",
          },
        ],
        date: [
          {
            required: true,
            message: "请选择出生日期",
            trigger: "change",
          },
        ],
      },
      sexOptions: [
        {
          label: "男",
          value: "男",
        },
        {
          label: "女",
          value: "女",
        },
      ],
      // token
      token: "",
    };
  },
  watch: {},
  created() {},
  mounted() {
    let token = sessionStorage.getItem("token");
    this.token = "Bearer" + " " + token;
  },
  methods: {
    ...mapMutations(["getuser"]),
    submitForm() {
      this.$refs["elForm"].validate(async (valid) => {
        if (!valid) return;
        let { data } = await edituser(this.user._id, this.user);
        if (data.code != 200) {
          return this.$message.error(data.msg);
        }
        this.getuser(data.user);
      });
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
    },
    // 上传文件成功
    handleAvatarSuccess(file) {
      this.getuser(file.user);
    },
    // 打开人脸登录对话框
    faceDialog() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.getCompetence();
      });
    },
    // 打开摄像头
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
        });
    },
    // 拍照
    setImage() {
      this.imgif = true;
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, 250, 250);

      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      window.sessionStorage.setItem("img", image);
      this.$message.success("拍照成功，请上传！！！");
    },
    //关闭摄像头并上传数据
    openFullScreen1() {
      let face = window.sessionStorage.getItem("img");
      if(!face){
        this.$message.info('尚未拍照！')
        this.dialogVisible = false
        return
      }
      this.thisVideo.srcObject.getTracks()[0].stop(), //关闭摄像头
        setTimeout(async () => {
          await edituser(this.user._id,{face:face})
          this.$message.success('上传成功！！！')
          //自己配置axios。
        }, 2000);
      this.dialogVisible = false
    },
  },
  computed: {
    ...mapState(["user"]),
  },
};
</script>
<style lang="scss" scoped>
::v-deep(.edit-user .el-card__body) {
  display: flex;
  align-items: center;
}
.el-form {
  margin-left: 20px;
}
</style>
